﻿Imports Org.BouncyCastle.X509
Imports SharedTools
Imports System.Xml.Serialization
Imports Org.BouncyCastle.Pkcs
Imports System.ComponentModel

Public Class CertificateItem
    Implements INotifyPropertyChanged


    Public Sub New(c As X509Certificate, username As String)
        Certificate = c
        Me.Username = username
    End Sub

    <Obsolete()> Public Sub New()

    End Sub

    Public Property Username As String
    <XmlIgnore()> Public ReadOnly Property ID As Integer
        Get
            Return CInt(Certificate.SerialNumber.ToString)
        End Get
    End Property

    <XmlIgnore()> Public ReadOnly Property CertificateType As CertificateType
        Get
            Dim ext = Certificate.GetExtensionValue(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage)
            Dim ku As New Org.BouncyCastle.Asn1.X509.KeyUsage(X509KeyUsage.DigitalSignature)

            If ku.GetString = ext.ToString Then
                Return CertificateType.Signature
            Else
                Return SharedTools.CertificateType.Cryptography
            End If
        End Get
    End Property

    <XmlIgnore()> Public Property Certificate As X509Certificate
    Public Property SerializableCertificate As Byte()
        Get
            Try
                Return Certificate.GetEncoded
            Catch ex As Exception
                Return Nothing
            End Try
        End Get
        Set(value As Byte())
            Try
                Dim parser = New X509CertificateParser
                Certificate = parser.ReadCertificate(value)
            Catch ex As Exception
                Certificate = Nothing
            End Try
        End Set
    End Property

    Public ReadOnly Property IsCurrent As Boolean
        Get
            Return Certificate IsNot Nothing AndAlso (Repository.CRL Is Nothing OrElse Repository.CRL.IsRevoked(Certificate) = False)
        End Get
    End Property

    Public ReadOnly Property Status As CertificateStatus
        Get
            If Certificate IsNot Nothing AndAlso Repository.CRL IsNot Nothing AndAlso Repository.CRL.IsRevoked(Certificate) Then
                Return CertificateStatus.Revoked
            End If
            If Certificate IsNot Nothing AndAlso Certificate.NotAfter < DateTime.Now Then
                Return CertificateStatus.Expired
            End If
            Return CertificateStatus.Current
        End Get
    End Property


    Public Sub Refresh()
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Status"))
    End Sub
    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
